import React, { useContext } from "react";
import { createUseStyles } from "react-jss";
import { ThemeContext } from "../../theme";
import { useErrmsgStyles } from "./styles";

const useStyles = createUseStyles({
  input: {
    borderRadius: "4px",
    border: "1px solid #D9D9D9",
    fontSize: (props: { fontSize: number }) => props.fontSize,
    color: "#333",
    padding: "3px 5px",
    "&::placeholder": {
      fontSize: "1em",
    },
    "&:hover": { borderColor: "#0B71BB" },
    "&:focus-visible": { borderColor: "#0B71BB", outline: 0 },
  },
});

export default function InputComponent({
  value,
  type,
  disabled,
  errmsg,
  onChange,
}: {
  value?: string | number;
  type?: "string" | "number";
  disabled?: boolean;
  errmsg?: string;
  onChange: (v: string | number) => void;
}) {
  const { fontSize } = useContext(ThemeContext);
  const classes = useStyles({ fontSize });
  const errClasses = useErrmsgStyles();

  const handler = (v: string | number = "") =>
    onChange(type == "number" ? Number(v) : v);

  return (
    <>
      <input
        type={type}
        className={classes.input}
        value={value ?? ""}
        onChange={(e) => handler(e.target.value)}
        disabled={disabled}
      />
      {errmsg && <div className={errClasses.errmsg}>{errmsg}</div>}
    </>
  );
}
